package org.easy.validator.core;

import org.easy.validator.resolver.PathVariableArgumentValidatorResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author volicy.xu
 */
public class ValidatorContextAware implements ApplicationContextAware, InitializingBean {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private ApplicationContext applicationContext;


    private static final Class PATH_CLASS = PathVariableMethodArgumentResolver.class;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("init - easyvalidator ....");
        RequestMappingHandlerAdapter requestMappingHandlerAdapter
                = applicationContext.getBean(RequestMappingHandlerAdapter.class);
        if (requestMappingHandlerAdapter != null) {
            ConfigurableWebBindingInitializer webBindingInitializer =
                    (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
            webBindingInitializer.setValidator(new ValidatorImpl(applicationContext));
            argumentResolvers(requestMappingHandlerAdapter);
        }
    }


    /**
     *
     * @param requestMappingHandlerAdapter
     */
    public void argumentResolvers(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        List<HandlerMethodArgumentResolver> resolvers =
                requestMappingHandlerAdapter.getArgumentResolvers()
                        .stream()
                        .filter(r -> !(r.getClass().equals(PATH_CLASS)))
                        .collect(Collectors.toList());
        resolvers.add(0,new PathVariableArgumentValidatorResolver());
        requestMappingHandlerAdapter.setArgumentResolvers(resolvers);
    }
}
